from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from api_key import get_api_key_by_api_key, get_api_key_by_key
import hashlib
import hmac
import logging
import os
import urllib
from api_key.handler import AddApiKey, EditApiKey, DeleteApiKey, ListApiKey
#from api_key import handler, get_api_key_by_api_key

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, webapp World!')
        
def verify_api_sig(request_url, secret_key, api_sig):
    # Note: Algorithm with secret key
    sig = hmac.new(secret_key, 
                   msg=request_url,
                   digestmod=hashlib.sha1).hexgigest()
    logging.info(sig)
    # print -> Python, GAE doesn't support print
    return api_sig == sig

def check_request(request):
    #0 Read necessary params
    api_key = request.get('api_key')
    api_sig = request.get('api_sig')
    api = get_api_key_by_api_key(api_key)
    if (not api or not api_sig):
        return False
    
    #1 Sort all params
    """
    param1=abc&param2=bcd&api_key=api_key_value&api_sig=api_sig_value
    param1=abc
    param2=bcd
    api_key=api_key_value
    api_sig=api_sig_value
    """
    params = dict([x.split('=') 
                   for x in request.query_string.split('&') ])
    del params['api_sig']
    
    #2 Remove api_sig
    tmp = params.items()
    tmp.sort()
    # join ~ implode (PHP)
    query_string = '&'.join([k+'='+urllib.quote(str(v)) 
                             for (k,v) in tmp])
    
    #3
    return verify_api_sig(request.path + "?" + query_string, 
                          api_key, api_sig)

class HttpServices(webapp.RequestHandler):
    def get(self):
        self.common(self, 'GET')
        pass
    
    def post(self):
        self.common(self, 'POST')
        pass
    
    def common(self, requestHandler, method):
        #self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
        
        if (not check_request(requestHandler.request)):
            self.response.set_status(500)
            self.response.out.write('{"exception":"%s"}' % "IncorrectSignatureException" )
            return
        
        #continue
        self.response.out.write('{"ok":"%s"}' % 0 )
        return
        
application = webapp.WSGIApplication([
        ('/sample/auth', HttpServices),
        ('/api_key/add', AddApiKey),
        ('/api_key/edit', EditApiKey),
        ('/api_key/delete', DeleteApiKey),
        ('/api_key/list', ListApiKey)
], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()